import { useState } from "react"
import { message, Modal, Select } from "antd"
import { itemType } from "./type"
import { GetRolesFnc, SaveRolesFnc } from '@/api/user'

const GiveRole = ({roleBox, changeRoleBox, userID, userName, roleName, init, ipt, pageNow, pageSize}: itemType) => {
  const [selectOptions, setSelectOptions] = useState<any>([]) // selectOption 选项
  const [value, setValue] = useState('')

  // slect获得焦点的时候 才去获取数据
  const getFocus = async () => {
    const res = await GetRolesFnc()
    if(res.data.meta.status === 200) {
      let options = res.data.data.map((item: {id: number, roleName: string}) => {
        return {
          id: item.id,
          label: item.roleName,
          value: item.roleName
        }
      })
      setSelectOptions(options)
    }
  }

  // 关闭dialog
  const closeDialog = () => {
    changeRoleBox(false)
    setValue('')
  }

  // 保存角色
  const saveRole = async () => {
    const res = await SaveRolesFnc(userID, {rid: selectOptions[0].id})
    if(res.data.meta.status === 200) {
      message.success('更新成功', 1.5, () => {
        changeRoleBox(false)
        init(ipt, pageNow, pageSize)
      })
    } 
  }

  return (
    <Modal title='分配用户' open={roleBox} cancelText='取消' okText='确定' onOk={saveRole} onCancel={() => closeDialog()}>
      <p>当前的用户: {userName}</p>
      <p style={{margin: '20px 0'}}>当前的角色: {roleName}</p>
      <span>分配角色 </span>
      <Select value={value} options={selectOptions} placeholder='请选择' style={{ width: 120 }} onFocus={getFocus} onChange={(value) => setValue(value)}/>
    </Modal>
  )
}

export default GiveRole